from app01 import models
from app01.utils.pagination import Pagination
from app01.utils.form import PrettyEditModelForm, PrettyModelForm, UserModelFrom


# Create your views here.

def depart_list(request):
    """部门列表"""
    # 1，去数据库中获取所有的部门列表
    queryset = models.Department.objects.all()

    page_object = Pagination(request, queryset, page_size=5)
    context = {
        'queryset': page_object.page_queryset,
        'page_string': page_object.html()
    }

    return render(request, 'depart_list.html', context)


def depart_add(request):
    """新增部门"""
    if request.method == "GET":
        return render(request, 'depart_add.html')

    # 获取用户post提交的的数据
    title = request.POST.get('title')
    # 获取到后保存到数据库
    models.Department.objects.create(title=title)

    # 重定向回列表页面
    return redirect("/depart/list/")


def depart_delete(request):
    """删除功能"""
    # 获取id
    nid = request.GET.get("nid")
    # 删除
    models.Department.objects.filter(id=nid).delete()
    # 重定向回列表页面
    return redirect("/depart/list/")


# nid参数是视图函数传来的值
def depart_edit(request, nid):
    """修改"""
    if request.method == 'GET':
        # 根据nid就可以获取那行的数控
        # first() 当只向获取第一个是不用在提起【获取nid那行
        row_object = models.Department.objects.filter(id=nid).first()

        return render(request, 'depart_edit.html', {'row_object': row_object})

    # 获取用户提交的title【标题
    title = request.POST.get('title')
    # 根据id找到数据库那行的数据并进行更新
    models.Department.objects.filter(id=nid).update(title=title)

    # 重定向回列表页面
    return redirect("/depart/list/")


def depart_multi(request):
    """ 批量上传（Excel文件） """

    from openpyxl import load_workbook

    # 1，获取用户传来的文件对象
    file_object = request.FILES.get('exc')
    # print(type(file_object))    # <class 'NoneType'>

    # 2，对象传给openpyxl  由openpyxl 打开文件
    wb = load_workbook(file_object)
    sheet = wb.worksheets[0]

    # 选择表中某个数据
    # call = sheet.call(1, 2)
    # print(call)

    # 3，循环获取每一行数据
    for row in sheet.iter_rows(min_row=2):
        text = row[0].value
        print(text)
        # 拿到文件上传的内容 再保存到数据库中
        exists = models.Department.objects.filter(title=text).exists()
        if not exists:
            models.Department.objects.create(title=text)
    return redirect("/depart/list/")

